/**
 * 
 */
package com.tnl.web.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tnl.web.dao.AdminUserDAO;
import com.tnl.web.dao.PermissionDAO;
import com.tnl.web.dao.RoleDAO;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.domain.Role;

/**
 * @author haigang.li
 *
 */
@Service
public class UserService {

	@Autowired
	private AdminUserDAO adminUserDAO;

	@Autowired
	private RoleDAO roleDAO;

	@Autowired
	private PermissionDAO permissionDAO;

	public AdminUser findById(Integer id) {
		return (AdminUser) adminUserDAO.findByID(id);
	}

	public AdminUser retrieveUserByName(String username) {
		AdminUser user = adminUserDAO.findByUsername(username);
		return user;
	}

	public AdminUser retrieveUser(String username, String password) {
		AdminUser user = adminUserDAO.findUser(username, password);
		return user;
	}

	public List<AdminUser> retrieveAllUsers() {
		return adminUserDAO.findAll();
	}

	public List<AdminUser> retrieveAllUsersExceptAdmin() {
		return adminUserDAO.findAllUsersExceptAdmin();
	}

	public void refresh(AdminUser user) {
		adminUserDAO.update(user);
	}

	public void createUser(AdminUser user) {
		adminUserDAO.save(user);
	}

	public void updateUser(AdminUser user) {
		adminUserDAO.update(user);
	}

	public boolean hasPermission(AdminUser user, String permissionName) {
		int roleId = user.getRoleId();
		Role role = roleDAO.getById(roleId);
		if (role == null) {
			return false;
		}
		return permissionDAO.checkPermission(roleId, permissionName);
//		List<Permission> permissions = permDAO.getRolesPermission(roleId);
//		if (permissions == null) {
//			return false;
//		}
//		role.setPermissions(permissions);
//		for (Permission perm : permissions) {
//			if (perm.getPermissionName().equals(permissionName)) {
//				return true;
//			}
//		}
//		return false;
		
	}
}
